package com.party.web.web.controller.crowdfund;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.*;
import com.party.core.model.label.Label;
import com.party.core.model.log.BehaviorType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.IAnalyzeService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IProjectLabelService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.label.ILabelService;
import com.party.web.biz.crowdfund.AnalyzeBizService;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.annotation.UserOperate;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.output.crowdfund.AnalyzeOutput;
import com.party.web.web.dto.output.crowdfund.TypeCountOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 众筹分析控制器
 * Created by wei.li
 *
 * @date 2017/7/10 0010
 * @time 14:31
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/crowdfund/analyze")
public class AnalyzeController {

    @Autowired
    private AnalyzeBizService analyzeBizService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IAnalyzeService analyzeService;

    @Autowired
    private IProjectLabelService projectLabelService;

    @Autowired
    private ILabelService labelService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;


    protected static Logger logger = LoggerFactory.getLogger(AnalyzeController.class);
    /**
     * 众筹分析列表
     *
     * @param projectAnalyze 众筹分析
     * @return 交互数据
     */
    @DataControl
    @RequestMapping(value = "list")
    public ModelAndView list(@ControlParam(table = {"zc_event", "activity"}, column = {"create_by", "member"},
            getMethodName = {"getEventId", "getTargetId"}, isProjectId = {false, false}) ProjectAnalyze projectAnalyze) {

        ModelAndView modelAndView = new ModelAndView("crowdfund/analyzeList");
        List<String> dateList = null;
        List<Label> labelList = null;
        TypeCountOutput countOutput = null;
        TypeCountOutput dpCountOutput = null;
        Double totalAmount = null;


        if(projectAnalyze!=null&&(StringUtils.isNotBlank(projectAnalyze.getTargetId())||StringUtils.isNotBlank(projectAnalyze.getEventId()))){

            dateList = analyzeBizService.dateStringList();
            labelList = labelService.list(new Label());
            countOutput = analyzeBizService.countList(projectAnalyze);
            dpCountOutput = analyzeBizService.countDirectList(projectAnalyze);
            totalAmount = projectService.sumForActualAmount(projectAnalyze,0);
        }

        modelAndView.addObject("dateList", JSONObject.toJSON(dateList));
        modelAndView.addObject("labelList", JSONObject.toJSON(labelList));
        modelAndView.addObject("count", countOutput);
        modelAndView.addObject("directCount", dpCountOutput);
        modelAndView.addObject("projectAnalyze", projectAnalyze);
        modelAndView.addObject("totalAmount", totalAmount);
        return modelAndView;
    }



    /**
     * 直接众筹分析列表
     *
     * @param projectAnalyze 众筹分析
     * @return 交互数据
     */
    @DataControl
    @RequestMapping(value = "directPayList")
    public ModelAndView directPayList(@ControlParam(table = {"zc_event", "activity"}, column = {"create_by", "member"},
            getMethodName = {"getEventId", "getTargetId"}, isProjectId = {false, false}) ProjectAnalyze projectAnalyze) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/analyzeDirectPayList");
        List<String> dateList = null;
        List<Label> labelList = null;
        TypeCountOutput countOutput = null;
        TypeCountOutput dpCountOutput = null;
        Double totalAmount = null;

        if(projectAnalyze!=null&&(StringUtils.isNotBlank(projectAnalyze.getTargetId())||StringUtils.isNotBlank(projectAnalyze.getEventId()))){

            dateList = analyzeBizService.dateStringList();
            labelList = labelService.list(new Label());
            countOutput = analyzeBizService.countList(projectAnalyze);
            dpCountOutput = analyzeBizService.countDirectList(projectAnalyze);

            totalAmount = projectService.sumForActualAmount(projectAnalyze,0);
        }

        modelAndView.addObject("dateList", JSONObject.toJSON(dateList));
        modelAndView.addObject("labelList", JSONObject.toJSON(labelList));
        modelAndView.addObject("count", countOutput);
        modelAndView.addObject("directCount", dpCountOutput);
        modelAndView.addObject("projectAnalyze", projectAnalyze);
        modelAndView.addObject("totalAmount", totalAmount);
        return modelAndView;
    }


    /**
     * 异步获取分析数据
     *
     * @param projectAnalyze
     * @param pageO
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/api/list")
    public Map<String, Object> ajaxData(ProjectAnalyze projectAnalyze, Page pageO) {
        List<AnalyzeOutput> outputList = analyzeBizService.list(projectAnalyze, pageO);
        //处理小于众筹时间开始的数据
        List<Date> dateDateList = analyzeBizService.dateList();
        for (AnalyzeOutput out : outputList) {
            String startDate = DateUtils.formatDate(out.getCreateDate(), "yy/MM/dd");
            Map<String, Double> map = out.getMoneyMap();
            for (Date dateData : dateDateList) {
                String strDate = DateUtils.formatDate(dateData, "yy/MM/dd");
                if (DateUtils.compareDate(dateData, out.getCreateDate()) == -1) {
                    if (!startDate.equals(strDate)) {
                        map.put(DateUtils.formatDate(dateData, "yy/MM/dd"), -1d);
                    }
                }
            }
        }
        Map<String, Object> ret = Maps.newHashMap();
        ret.put("data", outputList);
        ret.put("count", pageO.getTotalCount());
        ret.put("code", 0);
        return ret;
    }


    /**
     * 数据导出
     * @param projectAnalyze 众筹分析
     * @param response 导出数据
     * @return 交互
     */
    @DataControl
    @ResponseBody
    @UserOperate(moduleName = "众筹项目/主题-数据分析-众筹列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "listExport")
    public AjaxResult listExport(@ControlParam(table = {"zc_event", "activity"}, column = {"create_by", "member"},
            getMethodName = {"getEventId", "getTargetId"}, isProjectId = {false, false}) ProjectAnalyze projectAnalyze, HttpServletResponse response){
        String fileName =  DateUtils.todayDate() + ".xlsx";
        if (!Strings.isNullOrEmpty(projectAnalyze.getTargetId())){
            Activity activity = activityService.get(projectAnalyze.getTargetId());
            fileName = activity.getTitle() + DateUtils.todayDate() + ".xlsx";
        }
        else if (!Strings.isNullOrEmpty(projectAnalyze.getEventId())){
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectAnalyze.getEventId());
            fileName = crowdfundEvent.getName() + DateUtils.todayDate() + ".xlsx";
        }

        List<AnalyzeOutput> outputList = analyzeBizService.list(projectAnalyze, null);
        try {
            String allPath = analyzeBizService.export(fileName, outputList, response, YesNoStatus.NO.getCode());
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出联合发起的众筹异常", e);
        }
        return null;
    }


    /**
     *  直接付款数据导出
     * @param projectAnalyze 众筹分析
     * @param response 导出数据
     * @return 交互
     */
    @DataControl
    @ResponseBody
    @RequestMapping(value = "dpListExport")
    public AjaxResult dpListExport(@ControlParam(table = {"zc_event", "activity"}, column = {"create_by", "member"},
            getMethodName = {"getEventId", "getTargetId"}, isProjectId = {false, false}) ProjectAnalyze projectAnalyze, HttpServletResponse response){
        String fileName =  DateUtils.todayDate() + ".xlsx";
        if (!Strings.isNullOrEmpty(projectAnalyze.getTargetId())){
            Activity activity = activityService.get(projectAnalyze.getTargetId());
            fileName = activity.getTitle() + DateUtils.todayDate() + ".xlsx";
        }
        else if (!Strings.isNullOrEmpty(projectAnalyze.getEventId())){
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectAnalyze.getEventId());
            fileName = crowdfundEvent.getName() + DateUtils.todayDate() + ".xlsx";
        }

        List<AnalyzeOutput> outputList = analyzeBizService.list(projectAnalyze, null);
        try {
            String allPath = analyzeBizService.exportDirectPay(fileName, outputList, response);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出直接付款众筹异常", e);
        }
        return null;
    }

    /**
     * 修改朋友状态
     * @param  projectId 项目编号
     * @param status 状态
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "changeFriend")
    public AjaxResult changeFriend(String projectId, Integer status){
        AjaxResult ajaxResult = new AjaxResult();
        Analyze analyze = analyzeService.findByTargetId(projectId);
        analyze.setIsFriend(status);
        analyzeService.update(analyze);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    /**
     * 修改是否进群
     * @param projectId 项目编号
     * @param status 状态
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "changeGroup")
    public AjaxResult changeGroup(String projectId, Integer status){
        AjaxResult ajaxResult = new AjaxResult();
        Analyze analyze = analyzeService.findByTargetId(projectId);
        analyze.setIsGroup(status);
        analyzeService.update(analyze);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 修改是否做海报
     * @param  projectId 项目编号
     * @param status 状态
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "changePoster")
    public AjaxResult changePoster(String projectId, Integer status){
        AjaxResult ajaxResult = new AjaxResult();
        Analyze analyze = analyzeService.findByTargetId(projectId);
        analyze.setIsPoster(status);
        analyzeService.update(analyze);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 我的标签列表
     * @param projectId 项目编号
     * @return 交互数据
     */
    @RequestMapping(value = "labelView")
    public ModelAndView labelView(String projectId){
        ModelAndView modelAndView = new ModelAndView("crowdfund/distributionLabel");
        List<ProjectLabel> myLabelList = projectLabelService.findByProjectId(projectId);
        List<Label> labelList = labelService.list(new Label());
        modelAndView.addObject("myLabelList", myLabelList);
        modelAndView.addObject("labelList", labelList);
        modelAndView.addObject("projectId", projectId);
        return modelAndView;
    }


    /**
     * 保存标签
     * @param id 标签集合
     * @param projectId 项目编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "labelSave")
    public AjaxResult labelSave(String id, String projectId){
        AjaxResult ajaxResult = new AjaxResult();
        /*Set<String> idSet = Sets.newHashSet(Splitter.on(",").split(ids));*/
        String style = "";
        try {
            style = analyzeBizService.labelSave(id, projectId);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            return ajaxResult;
        }
        ajaxResult.setData(style);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    @ResponseBody
    @RequestMapping(value = "init")
    public AjaxResult init(){
        List<Project> projectList = projectService.list(new Project());
        for (Project project : projectList){
            Analyze analyze = new Analyze();
            analyze.setTargetId(project.getId());
            analyzeService.insert(analyze);
        }
        return AjaxResult.success();
    }
}
